package edu.stanford.bmir.protege.web.client.ui.ontology.stkos.merger.currenttree;

import java.util.Collection;

import com.gwtext.client.core.Function;
import com.gwtext.client.widgets.tree.TreeNode;

import edu.stanford.bmir.protege.web.client.project.Project;
import edu.stanford.bmir.protege.web.client.rpc.data.EntityData;
import edu.stanford.bmir.protege.web.client.ui.ontology.stkos.common.GWTExtUtil;
import edu.stanford.bmir.protege.web.client.ui.ontology.stkos.common.StkosPanelType;
import edu.stanford.bmir.protege.web.client.ui.ontology.stkos.merger.common.StkosMergerClassTreePanel;
import edu.stanford.bmir.protege.web.client.ui.portlet.AbstractOWLEntityPortlet;

public class StkosMergerCurrentTreePortlet extends AbstractOWLEntityPortlet {

	private StkosMergerClassTreePanel classTreePanel;

	private StkosPanelType type;
	
	private Project accordingProject;

	public StkosMergerCurrentTreePortlet(Project project) {
		super(project);
	}

	@Override
	public Collection<EntityData> getSelection() {
		return null;
	}

	@Override
	public void onRefresh() {
		if (isClassTreePanelActivity()) {
			classTreePanel.refreshTreeNode(getSelectedTreeNode());
		}
	}

	@Override
	public void reload() {
	}

	@Override
	public void initialize() {
		setHeight(500);

		showPanel(StkosPanelType.CLASS_TREE);
	}

	public void setAccordingProject(Project accordingProject) {
		this.accordingProject = accordingProject;
		if(classTreePanel!=null){
			classTreePanel.setAccordingProject(accordingProject);
		}
	}
	
	public void showPanel(StkosPanelType type) {
		removeAll();
		this.type = type;
		if (StkosPanelType.CLASS_TREE.equals(type)) {
			setTitle("当前本体类树");
			if (classTreePanel == null) {
				addClassTreePanel();
			} else {
				classTreePanel.show();
			}
		} else {
			setTitle("当前本体树");
		}
		doLayout();
	}

	public boolean isClassTreePanelActivity() {
		boolean f = false;
		if (classTreePanel != null && StkosPanelType.CLASS_TREE.equals(type)) {
			f = true;
		}
		return f;
	}

	protected void addClassTreePanel() {
		classTreePanel = new StkosMergerClassTreePanel(getProject(),this.accordingProject);
		classTreePanel.addListener(GWTExtUtil.EVENT_ONSELECTIONCHANGE,
				new Function() {
					@Override
					public void execute() {
						fireOnSelectionChangeEvent();
					}
				});
		add(classTreePanel);
		doLayout();
	}

	protected void fireOnSelectionChangeEvent() {
		fireEvent(GWTExtUtil.EVENT_ONSELECTIONCHANGE);
	}

	public TreeNode getSelectedTreeNode() {
		TreeNode treeNode = null;
		if (isClassTreePanelActivity()) {
			treeNode = classTreePanel.getSelectionModel().getSelectedNode();
		}
		return treeNode;
	}

	public StkosPanelType getActivityPanel() {
		return type;
	}
}
